#include "RLBufFile.h"

void RLBufFile_init(RLBufFile *buffile, FILE *onlyreadfile, unsigned char *buf, unsigned int buf_len) {
    buffile->file = onlyreadfile;
    buffile->buf = buf;
    buffile->buf_len = buf_len;
    buffile->data_len = 0;
    buffile->index = 0;
}

int RLBufFile_read_byte(RLBufFile *buffile, unsigned char *ch) {
    unsigned int len;
    if (buffile->index >= buffile->data_len) {
        len = fread(buffile->buf, 1, buffile->buf_len, buffile->file);
        buffile->index = 0;
        if (len == -1) {
            return RLBUFFILE_RET_ERROR;
        } else if (len == 0) {
            if (buffile->data_len != 0) {
                *ch = -1;
                buffile->data_len = 0;
                return RLBUFFILE_RET_EOF;
            } else {
                return RLBUFFILE_RET_ERROR;
            }
        }
        buffile->data_len = len;
    }
    *ch = buffile->buf[buffile->index];
    buffile->index++;
    return RLBUFFILE_RET_SUCCEED;
}

int RLBufFile_read_back(RLBufFile *buffile) {
    if (buffile->index > 0) {
        buffile->index--;
    } else {
        fseek(buffile->file, -buffile->data_len, SEEK_CUR);
        buffile->data_len = fread(buffile->buf, 1, buffile->buf_len, buffile->file);
        if (buffile->data_len == -1) {
            return RLBUFFILE_RET_ERROR;
        } else if (buffile->data_len == 0) {
            return RLBUFFILE_RET_EOF;
        } else {
            buffile->index = buffile->data_len - 1;
        }
    }
    return RLBUFFILE_RET_SUCCEED;
}